import Snake from "./Snake";
import Food from "./food";
import ScorePanel from "./ScorePanel";
class GameControl{
    snake: Snake;
    food: Food;
    scorelPanel: ScorePanel;

    direction: string = "";

    isLive: boolean = true;



    constructor(){
        this.snake = new Snake();
        this.food = new Food();
        this.scorelPanel = new ScorePanel();

        this.init();
    }

    init(){
        document.addEventListener('keydown', this.keydownHandler.bind(this));
        this.run();
        
    }

    // 监听方法
    keydownHandler(event: KeyboardEvent){
        // ArrowUp  ArrowDown ArrowLeft ArrowRight
        // IE Up Down Left Right
        const List = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Left", "Right", "Up", "Down"];
        if(List.includes( event.key)){
            this.direction = event.key;
        }
    }

    run(){
        let x: number = this.snake.X;
        let y: number = this.snake.Y;

        switch (this.direction){
            case "ArrowUp":
                case "Up":
                    y -= 10;
                    break;
            case "ArrowDown":
                case "Down":
                    y += 10;
                    break;
            case "ArrowLeft":
                case "Left":
                    x -= 10;
                    break;
            case "ArrowRight":
                case "Right":
                    x += 10;
                    break;
        }

        if(x>290 || x<0 || y<0 || y>310){
            x = 0
            y = 0
            this.direction = "";
            this.gameOver();
            this.snake.X = x;
            this.snake.Y = y;
            return;
        }

        this.snake.X = x;
        this.snake.Y = y;

        const foodX = this.food.X;
        const foodY = this.food.Y;

        if(x===foodX&&y===foodY){
            this.scorelPanel.addScore();
            this.food.setPosition();
            this.snake.addBody();
        }

        this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorelPanel.level - 1)*30);
    }

    gameOver(){
        alert("游戏结束")
    }

    start(){

    }

    stop(){

    }
}

export default GameControl;